package com.changgou.seckill.service.impl;

import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.service.SeckillGoodsService;
import com.changgou.seckill.task.SeckillGoodsPushTask;
import com.changgou.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Author: HuangFu
 * @Date: 2020/2/23 10:05
 * @Description:
 */
@Service
public class SeckilGoodsServiceImpl implements SeckillGoodsService {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查询当前秒杀商品
     * @param ids
     * @param date
     * @return
     */
    @Override
    public List<SeckillGoods> findCurSeckillGoods(Set ids, Date date) {
        Example example = new Example(SeckillGoods.class);
        Example.Criteria criteria = example.createCriteria();
        //审核通过
        criteria.andEqualTo("status","1");
        //商品库存个数>0
        criteria.andGreaterThan("stockCount",0);
        //秒杀商品开始时间>=当前时间段
        criteria.andGreaterThanOrEqualTo("startTime",date);
        //秒杀商品结束<当前时间段+2小时
        criteria.andLessThan("endTime", DateUtil.addDateHour(date,2));
        // 排除之前已经加载到Redis缓存中的商品数据
        if(!ids.isEmpty()){
            criteria.andNotIn("id",ids);
        }

        return seckillGoodsMapper.selectByExample(example);
    }

    /**
     * 查询所有秒杀商品 根据时间
     * @param time
     * @return
     */
    @Override
    public List<SeckillGoods> list(String time) {
        return redisTemplate.boundHashOps(SeckillGoodsPushTask.SECKILL_GOODS_KEY+time).values();
    }
}
